<template>
  <div>
    <page-header />
    <!-- 订单基本信息 -->
    <div class="order-container">
      <h2><i class="back-icon el-icon-back" @click="goBack" /> 订单详情</h2>
      <div class="deliery-div">
        <p style="color:#66b1ff">收货信息：</p>
        <el-row>
          <el-col :span="4">收获地址</el-col>
          <el-col :span="20">{{ address?
            address.province +
            address.city +
            address.town +
            " " +
            address.detail:'暂无'
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">收件人</el-col>
          <el-col :span="20">{{ address? address.username:'暂无' }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">手机号</el-col>
          <el-col :span="20">{{ address?address.phone:'暂无' }}</el-col>
        </el-row>
      </div>
      <el-divider />
      <div class="order-message-div">
        <p style="color:#66b1ff">订单信息：</p>
        <el-row>
          <el-col :span="4">订单编号</el-col>
          <el-col :span="20">{{ orderDetailArr[0].orderNum }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">下单时间</el-col>
          <el-col :span="20">{{ orderDetailArr[0].createTime }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">物流</el-col>
          <el-col v-if="logistics" :span="20">
            {{ logistics?logistics.logisticsTypeQo.name :'暂无' }}
            <el-link
              type="primary"
              href="https://www.kuaidi100.com/?from=openv"
              target="_blank"
            >{{ logistics?logistics.logNum :'暂无' }}</el-link>
          </el-col>
          <el-col v-else :span="20">暂无</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">订单状态</el-col>
          <el-col :span="20">
            <template v-if="orderDetailArr[0].status === 0">未支付</template>
            <template
              v-else-if="
                orderDetailArr[0].status === 1 || orderDetailArr[0].status === 2
              "
            >待收货</template>
            <template
              v-else-if="orderDetailArr[0].status === 3"
            >已取消</template>
            <template
              v-else-if="orderDetailArr[0].status === 4"
            >已完成</template>
            <template
              v-else-if="orderDetailArr[0].status === 5"
            >已取消</template>
          </el-col>
        </el-row>
      </div>
      <el-divider />
      <!-- 购买商品信息 -->
      <div class="order-detail-div">
        <el-table :data="orderDetailArr" style="width: 100%">
          <el-table-column label="商品信息" width="300">
            <template slot-scope="scope">
              <div class="book-img-des-container">
                <div class="book-img">
                  <el-image
                    style="width: 100%; height: 100%"
                    :src="scope.row.book.bookImgs.length > 0?scope.row.book.bookImgs[0].imgName:''"
                  />
                  <!-- scope.row.book.bookImgs.length > 0?scope.row.book.bookImgs[0].imgName:'' -->
                  <!-- scope.row.book?scope.row.book.bookImgs[0].imgName:'' -->
                </div>
                <div class="book-des">
                  <div class="book-name">
                    <span>{{ scope.row.book? scope.row.book.bookName :'暂无' }}</span>
                  </div>
                  <div class="book-author">
                    <span>{{ scope.row.book? scope.row.book.author :'暂无' }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价">
            <template slot-scope="scope">
              <span style="color: #f40">￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="num" />
          <el-table-column label="总金额">
            <template slot-scope="scope">
              <span
                style="color: #f40"
              >￥{{ scope.row.price * scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-row>
                <el-col v-if="scope.row.status === 3 || scope.row.status === 4 || scope.row.status === 5" :span="12">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index,scope.row)"
                  >删除</el-button>
                </el-col>
                <el-col v-if="scope.row.status === 0 || scope.row.status === 1" :span="12">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)"
                  >修改</el-button>
                </el-col>
                <el-col v-if="scope.row.status === 0" :span="12">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handlePay(scope.$index, scope.row)"
                  >支付</el-button>
                </el-col>
              </el-row>
              <el-row style="margin-top:10px">
                <el-col v-if="scope.row.status === 0" :span="12">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="cancelOrder(scope.$index, scope.row)"
                  >取消</el-button>

                </el-col>
                <el-col v-if="scope.row.status === 2" :span="12">
                  <el-button
                    size="mini"
                    type="success"
                    @click="deliveryOrder(scope.$index, scope.row)"
                  >确认收货</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      title="选择收货地址"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-row>
        <el-col :span="24">
          <el-radio
            v-for="(item,index) in addressList"
            :key="index"
            v-model="selectAddId"
            :label="item.id"
            border
            class="radio-sel"
          >{{ item.province + item.city + item.town + item.detail+ ' ' + item.phone + ' ' + item.username + '(收)' }}
          </el-radio>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSelectAddId">取 消</el-button>
        <el-button type="primary" @click="doSelectAdd">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="支付"
      :visible.sync="paydialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>是否确认支付</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPay">取 消</el-button>
        <el-button type="primary" @click="doPay">确 定</el-button>
      </span>
    </el-dialog>
    <right-bottom-fixd />
  </div>
</template>
<script>
import RightBottomFixd from '@/components/RightBottomFixd'
import PageHeader from '@/components/PageHeader'
import { delOrder, updateOrder, updateOrderStatus, payOrders } from '@/api/order'
import { getUserInfoAndAddress } from '@/common/common'
export default {
  components: {
    RightBottomFixd,
    PageHeader

  },
  data() {
    return {
      loading: false,
      // 修改收货地址id
      selectAddId: '',
      dialogVisible: false,
      paydialogVisible: false
    }
  },
  computed: {

    orderDetailArr() {
      const arr = []
      arr.push(this.$store.getters.orderDetail)
      // console.log(arr)
      return arr
    },
    address() {
      // console.log(this.$store.getters.orderDetail.address)
      return this.$store.getters.orderDetail.address
    },
    logistics() {
      return this.$store.getters.orderDetail.logistics
    },
    book() {
      return this.$store.getters.orderDetail.book
    },
    addressList() {
      // console.log(this.$store.getters.userAddressList)
      return this.$store.getters.userAddressList
    },
    userDetail() {
      return this.$store.getters.userDetail
    }
  },
  created() {
    this.getOrderDetail()
    this.getUserInfoAndAdd()
  },
  methods: {
    // 支付订单
    handlePay() {
      this.paydialogVisible = true
    },
    cancelPay() {
      this.paydialogVisible = false
    },
    // 确定支付
    doPay() {
      // 更改订单状太为成功支付
      this.loading = true
      const payOrderList = []
      const order = {
        id: this.orderDetailArr[0].id,
        status: 1
      }
      payOrderList.push(order)

      payOrders(payOrderList).then(res => {
        // 支付成功
        this.$notify({
          title: '成功',
          message: '成功支付',
          type: 'success'
        })
        this.loading = false
        // this.getOrderDetail()
        setTimeout(() => {
          this.$router.push('/profile/3')
        }, 1000)
      }).catch(() => {
        // 支付失败
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '支付失败'
        })
      })
      // 跳转订单页面
    },
    // 取消3，完成4，超时的订单5可以删除
    handleDelete(index, obj) {
      // 取消，完成，超时的订单可以删除
      if (obj.status === 3 || obj.status === 4 || obj.status === 5) {
        this.$confirm('是否删除该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          const obj = {
            uid: this.userDetail.id,
            oid: this.$route.params.id
          }
          delOrder(obj).then(res => {
            this.$notify({
              title: '成功',
              message: '取消订单成功',
              type: 'success'
            })
            this.$router.push('/profile/3')
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            })
          })
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '当前订单不可删除'
        })
      }
    },

    // 取消订单：0
    cancelOrder(index, obj) {
      // 未支付订单才能取消
      if (obj.status === 0) {
        this.$confirm('是否取消订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const arr = []
          const orderQo = {
            id: this.$route.params.id,
            status: 3
          }
          arr.push(orderQo)
          updateOrderStatus(arr).then(res => {
            this.loading = false
            this.$notify({
              type: 'success',
              title: '成功',
              message: '取消订单成功'
            })
            // 返回订单页面
            this.$router.push('/profile/3')
          }).catch(() => {
            this.loading = false
            this.$notify.error({
              title: '错误',
              message: '修改失败'
            })
          })
        }).catch(() => {})
      } else {
        this.$notify.error({
          title: '错误',
          message: '当前订单不能取消'
        })
      }
    },

    // 订单发货之后才能确认收货 2
    deliveryOrder() {
      // 把订单状态改为已完成
      this.loading = true
      const arr = []
      const orderQo = {
        id: this.$route.params.id,
        status: 4
      }
      arr.push(orderQo)
      updateOrderStatus(arr).then(res => {
        this.loading = false
        this.$notify({
          type: 'success',
          title: '成功',
          message: '确认收货成功'
        })
        // 回到订单列表
        setTimeout(() => {
          this.$router.push('/profile/3')
        }, 2000)
      }).catch(() => {
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '操作失败'
        })
      })
    },
    doSelectAdd() {
      this.loading = true
      // 构造obj提交修改
      const orderQo = {
        orderAdd: this.selectAddId
      }
      updateOrder(this.$route.params.id, orderQo).then(res => {
        // 修改用户收货地址成功
        this.getOrderDetail().then(res => {
          this.loading = false
          this.dialogVisible = false
          this.$notify({
            type: 'success',
            title: '成功',
            message: '修改成功'
          })
        })
      }).catch(() => {
        this.dialogVisible = false
        this.loading = false
        // 修改失败
        this.$notify.error({
          title: '错误',
          message: '修改失败'
        })
      })
      // 重新刷新页面
    },
    cancelSelectAddId() {
      this.dialogVisible = false
      this.setSelectAddId()
    },
    setSelectAddId() {
      this.selectAddId = this.address.id
    },
    async getUserInfoAndAdd() {
      await getUserInfoAndAddress()
      this.setSelectAddId()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.setSelectAddId()
        })
        .catch(_ => {})
    },
    async getOrderDetail() {
      this.$store.dispatch('order/getOrderDetailById', this.$route.params.id).then(res => {
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },

    // 修改订单收货地址 0，1
    handleEdit(index, obj) {
      // 订单未支付：0，未发货：1才能修改，而且只能修改收货地址（选择的）
      if (obj.status === 0 || obj.status === 1) {
        // 打开收货地址框，选择收货地址
        this.dialogVisible = true
      } else {
        this.$notify.error({
          title: '错误',
          message: '当前订单不可修改'
        })
      }
    },
    goBack() {
      this.$router.push('/profile/3')
    }
  }

}
</script>
<style lang="scss" scoped>
.back-icon:hover {
  color: #77baff;
}

.radio-sel{
  margin-left: 20px !important;
  margin-bottom: 8px;
}
.order-container {
  // background-color: hotpink;
  height: 500px;
  margin-top: 50px;
  margin-left: 200px;
  margin-right: 200px;
  margin-bottom: 120px;
  .deliery-div {
    margin: 0 20px;
    .el-row {
      margin-top: 10px;
    }
  }
  .order-message-div {
    margin: 0 20px;
    .el-row {
      margin-top: 10px;
    }
  }
  .order-detail-div {
    .book-img-des-container {
      display: flex;
      .book-img {
        width: 80px;
        height: 80px;
      }
      .book-des {
        margin-left: 20px;
        display: flex;
        flex-direction: column;
        .book-name,
        .book-author {
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.title {
  background-color: #e8f2ff;
}
</style>
